iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 13
0
Modern Web

初學者前端應用30天系列 第 13

[DAY13] js 陣列常用語法(下)

  • 分享至 

  • xImage
  •  

此篇繼續介紹更多陣列的用法。

fill

將指定範圍的陣列修改。

originarray:["one","two","three","four","five","six"],
exex:[],

("change", 2,5),change表示要替換的值,2和5表示範圍,2為該陣列的第3筆,5為第5筆。

this.exex= this.originarray.fill("change", 2,5)
console.log(this.exex)//輸出["one", "two", "change", "change", "change", "six"]

splice

刪除陣列裡指定範圍的元素再新增。

originarray:["one","two","three","four","five","six","seven"],

(4, 2,"nor","test","math"):從索引值4的地方(第五筆),刪除2筆值,並新增"nor","test","math"這三個字串到陣列裡。

this.originarray.splice(4, 2,"nor","test","math");
console.log(this.originarray)
//輸出[ "one", "two", "three", "four", "nor", "test", "math", "seven" ]

pop

移除該陣列最後一筆值。

originarray:["one","two","three","four","five","six","seven"],
exex:null,
this.exex = this.originarray.pop()
console.log(this.exex)
//輸出seven
console.log(this.originarray)
//輸出["one", "two", "three", "four", "five", "six"]

shift

移除該陣列第一筆值。

originarray:["one","two","three","four","five","six","seven"],
exex:null,
this.exex = this.originarray.shift()
console.log(this.exex)
//輸出one
console.log(this.originarray)
//輸出["two", "three", "four", "five", "six", "seven"]

concat

將兩個陣列合併。

arraytest:["new"],
bigarray:[],
originarray:["one","two","three","four","five","six","seven"],

this.originarray.concat(this.arraytest):將arraytest這個陣列合併到originarray陣列。

this.bigarray = this.originarray.concat(this.arraytest)
console.log(this.bigarray)
//輸出["one", "two", "three", "four", "five", "six", "seven", "new"]

join

合併該陣列和轉字串。

originarray:["one","two","three","four","five","six","seven"],
exex:null,
this.exex = this.originarray.join()
console.log(typeof(this.exex)
//輸出string
console.log(this.exex)
//one,two,three,four,five,six,seven

也可以在括號裡面輸入字串,改變陣列之間連接的值。

this.exex = this.originarray.join("----")
console.log(typeof(this.exex))
//輸出string
console.log(this.exex)
//輸出one----two----three----four----five----six----seven

slice

擷取指定範圍的陣列之值。

originarray:["one","two","three","four","five","six","seven"],
exex:null,

slice(1, 5):抓取該陣列索引值1到4(不包括索引值5的值)。

this.exex = this.originarray.slice(1, 5)
console.log(this.exex)
//輸出["two", "three", "four", "five"]

sort

排序陣列(只排第一個字元,若相同則比較第二個)。

originarray:["one","two","three","four","five","six","seven"],
numarray:[87,62,456,70,9,7,8456,39,563],
this.numarray.sort()
this.originarray.sort()
console.log(this.numarray)
//輸出[39, 456, 563, 62, 7, 70, 8456, 87, 9]
console.log(this.originarray)
//輸出["five", "four", "one", "seven", "six", "three", "two"]

上一篇
[DAY12] js 陣列常用語法(上) 12
下一篇
[DAY14]vuex 簡單介紹
系列文
初學者前端應用30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言